<template>
  <div class="allot-authority">
    <el-dialog title="分配权限" :visible="showDialog" @close="close">
      <!-- 权限是一颗树 -->
      <!-- 将数据绑定到组件上 -->
      <!-- check-strictly 如果为true 那表示父子勾选时  不互相关联 如果为false就互相关联 -->
      <!-- id作为唯一标识 -->
      <el-tree
        ref="permTree"
        :data="permData"
        :props="defaultProps"
        :show-checkbox="true"
        :check-strictly="true"
        :default-expand-all="true"
        :default-checked-keys="selectCheck"
        node-key="id"
      />
      <!-- 确定 取消 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="small" @click="btnPermOK">确定</el-button>
          <el-button size="small" @click="close">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permisson'
import { getRoleDetail, assignPerm } from '@/api/setting'
import { tranListToTreeDate } from '@/utils'
export default {
  name: 'AllotAuthority',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    // 用来记录分配角色的id
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      defaultProps: {
        label: 'name'
      },
      permData: [], // 专门用来接收权限数据 树形数据
      selectCheck: [] // 定义一个数组来接收 已经选中的节点
      // roleId: null
    }
  },
  computed: {

  },
  created() {
    this.getPermissionList()
  },
  methods: {
    async getPermissionList() {
      this.permData = tranListToTreeDate(await getPermissionList(), '0')
      this.$nextTick(async() => {
        const { permIds } = await getRoleDetail(this.roleId)
        this.selectCheck = permIds // 将当前角色所拥有的权限id赋值
      })
    },
    // 确认
    async btnPermOK() {
      // 调用el-tree的方法
      // console.log(this.$refs.permTree.getCheckedKeys())
      await assignPerm({ permIds: this.$refs.permTree.getCheckedKeys(), id: this.roleId })
      this.$message.success('分配权限成功')
      this.$emit('update:showDialog', false)
    },
    // 关闭
    close() {
      this.selectCheck = [] // 重置数据
      this.$emit('update:showDialog', false)
    }
  }
}
</script>

<style lang="less" scoped>

</style>
